package com.tanger.pay.wechat;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description map和xml互相转换工具
 * @Author Hchenbin
 * @Date 2024-01-04 17:21
 * @Version 1.0
 */
public class MapXmlUtil {

    public static String map2Xml(Map<String, String> map) {
        Element root = DocumentHelper.createElement("root");
        Document document = DocumentHelper.createDocument(root);
        for (String key : map.keySet()) {
            Element element = root.addElement(key);
            element.addText(map.get(key));
        }
        return document.asXML();
    }

    public static Map<String, String> xml2Map(String xml) {
        Map<String, String> respMap = new HashMap<String, String>();
        Document respDoc = null;
        try {
            respDoc = DocumentHelper.parseText(xml);
        }catch (Exception e){
            //logger
        }
        Element root = respDoc.getRootElement();
        List<Element> childList = root.elements();
        for (Element child : childList) {
            respMap.put(child.getName(), (String) child.getData());
        }
        return respMap;
    }
}
